package com.coinworld.config.intercepors;

import com.alibaba.fastjson.JSON;
import com.coinworld.entity.vo.Code2SessionVo;
import com.coinworld.object.HttpJsonResult;
import com.coinworld.redis.RedisPool;
import com.coinworld.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Resource
    private UserService userService;

    @Autowired
    private RedisPool redisPool;

    /**
     *  key过期时间（秒）
     */
    private final int EXPIRATIONTIME_SECONDS = 1;
    /**
     * key 前缀，防止和其他地方的key可以冲突
     */
    private final String prefix = "ip:";


//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        HttpJsonResult httpJsonResult = new HttpJsonResult();
//        String ip = getIp(request);
//        logger.info("ip:" + ip);
//
//        if (!StringUtils.isEmpty(ip)) {
//            //判断ip是否在黑名单里
//            String blackListKey = prefix + "blacklist";
//            if (redisPool.sismember(blackListKey, ip, 2)) {
//                httpJsonResult.setSuccess(false);
//                httpJsonResult.setCode(-5);
//                httpJsonResult.setMsg("请求次数太多，已被限制！");
//                setReturnJson(response, httpJsonResult);
//                return false;
//            }
//            //ip请求次数限制，一秒中50次被认为恶意刷接口
//            String key = prefix + "limit:" + ip;
//            boolean exists = redisPool.exists(key, 2);
//            if (exists) {
//                Long counts = redisPool.incr(key,EXPIRATIONTIME_SECONDS, 2);
//                if (counts > 50) {
//                    logger.info("limitip:" + ip);
//                    //直接加入黑名单
//                    redisPool.sadd(blackListKey, ip, 2);
//                    httpJsonResult.setSuccess(false);
//                    httpJsonResult.setCode(-6);
//                    httpJsonResult.setMsg("请求次数过多，请稍后在试！");
//                    setReturnJson(response, httpJsonResult);
//                    return false;
//                }
//            } else {
//                redisPool.setex(key, EXPIRATIONTIME_SECONDS, "1", 2);
//            }
//        }
        //判断是否被封号
//        String sessionId = request.getParameter("session_id");
//
//        if(!StringUtils.isEmpty(sessionId))
//        {
//            Integer userStatus = userService.getUserStatus(sessionId);
//            if(userStatus!=null && 0 == userStatus)
//            {
//                httpJsonResult.setSuccess(false);
//                httpJsonResult.setCode(-7);
//                httpJsonResult.setMsg("账号已被禁用！");
//                setReturnJson(response, httpJsonResult);
//                return false;
//            }
//        }
//        return true;
//    }

    private void setReturnJson(HttpServletResponse response, HttpJsonResult<Code2SessionVo> httpJsonResult) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset-utf-8");
            PrintWriter out = response.getWriter();
            out.append(JSON.toJSONString(httpJsonResult));
        } catch (Exception ex) {

        }
    }

    private String getIp(HttpServletRequest request)
    {
        // 获取请求IP
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)){
            ip = "" + request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)){
            ip = "" + request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)){
            ip = "" + request.getRemoteAddr();
        }
        if(StringUtils.isEmpty(ip)){
            return "";
        }
        int index = ip.indexOf(",");
        if(index != -1){
            ip = ip.substring(0,index);
        }
        return  ip;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
